using System.Collections.Generic;
using System.IO;
using YamlDotNet.RepresentationModel;

public class ConfigLoader
{
    private readonly YamlMappingNode _root;

    public ConfigLoader(string filePath = "application.yml")
    {
        var yaml = new YamlStream();
        using (var reader = new StreamReader(filePath))
        {
            yaml.Load(reader);
        }
        _root = (YamlMappingNode)yaml.Documents[0].RootNode;
    }

    // 获取 cluster.peers 字典
    public Dictionary<string, string> GetClusterPeers()
    {
        var clusterNode = (YamlMappingNode)_root.Children[new YamlScalarNode("cluster")];
        var peersNode = (YamlMappingNode)clusterNode.Children[new YamlScalarNode("peers")];
        var peers = new Dictionary<string, string>();
        foreach (var entry in peersNode.Children)
        {
            peers[entry.Key.ToString()] = entry.Value.ToString();
        }
        return peers;
    }

    // 可扩展：根据路径获取任意 Mapping
    public Dictionary<string, string> GetDictionaryByPath(params string[] path)
    {
        YamlMappingNode node = _root;
        foreach (var key in path)
        {
            node = (YamlMappingNode)node.Children[new YamlScalarNode(key)];
        }
        var dict = new Dictionary<string, string>();
        foreach (var entry in node.Children)
        {
            dict[entry.Key.ToString()] = entry.Value.ToString();
        }
        return dict;
    }

    // 通过路径字符串（如 "cluster.peers"）获取字典
    public Dictionary<string, string> GetDict(string path)
    {
        var keys = path.Split('.');
        YamlMappingNode node = _root;
        foreach (var key in keys)
        {
            node = (YamlMappingNode)node.Children[new YamlScalarNode(key)];
        }
        var dict = new Dictionary<string, string>();
        foreach (var entry in node.Children)
        {
            dict[entry.Key.ToString()] = entry.Value.ToString();
        }
        return dict;
    }
} 